﻿/**
 * jiangliwu 
 * 2016年03月31日16:20:11
 * 基本开发框架
**/
using UnityEngine;
using UnityEngine.SceneManagement;
using System.Collections;



namespace VFramework{

	/**
	 * 框架初始化类
	 * 一定要放在摄像机的下面
	**/

	public class VFrameworkInitializer : MonoBehaviour {

		public bool showFPS = true;
		public bool screenLogClose = false;
		private static int _vframeworkCounter = 0;



		void Awake(){
			if (++_vframeworkCounter > 1) {
				throw new UnityException ("VFramework only attach on Camera once!");
			}

			if (GetComponent<Camera> () == null) {
				throw new UnityException ("VFramework only attach on Camera!");
			}

			beforeInit ();
			init ();
		}

		void Start () {
			
		}



		void beforeInit(){
			
			// fps
			if (showFPS) {
				gameObject.AddComponent<FPSCounter> ();
			}


			// logger
			VLogger.getInstance ().setLogger (new ConsoleLogger (), new LogLevel[]{ 
				LogLevel.DEBUG,LogLevel.WARN,LogLevel.INFO,LogLevel.ERROR
			});
			VLogger.getInstance ().setLogger (ScreenLogger.create(gameObject), new LogLevel[]{ 
				LogLevel.DEBUG,LogLevel.WARN,LogLevel.INFO,LogLevel.ERROR
			});
			VLogger.screenClose (screenLogClose);

			// music, effect , light
			SystemMgr.getInstance ().initEvent ();
			SystemMgr.getInstance ().initAudio(GetComponent<Camera>());

			VLogger.info ("VFrameworkInitializer::beforeInit success !!!");

			// common ui
			gameObject.AddComponent<VUICommonDisplay>();


			//extensions
		}

		void init(){


			EventMgr.getInstance ().addEvent (FrameEvents.LOAD_SCENE_BY_NAME, delegate(EventData eventData) {
				string name = (string)ArgsWarp.getValue("name",eventData.data);
				bool asyn =  (bool)ArgsWarp.getValue("asyn",eventData.data);



				release();	//清理

				if(asyn == true){
					return SceneManager.LoadSceneAsync(name);
				}else{
					SceneManager.LoadScene(name);
					return null;
				}

			});

            //EventMgr.getInstance().dispatchEvent(FrameEvents.AFTER_INIT,0);
			VLogger.info ("VFrameworkInitializer::init success !!!");
		}
		
		// Update is called once per frame
		void Update () {
		
		}

		void release(){
			_vframeworkCounter = 0;

			SystemMgr.getInstance ().release ();
			EventMgr.getInstance ().release ();
			VLogger.info("VFrameworkInitializer::release success !!!");
			VLogger.getInstance ().release ();
		}

	}

}
